/*
 * JSONP模块
 * dev@doc.moe
 * lxrmido@lxrmido.com
 */
var _JSONP_KV = {
	
};
var _JSONP_CX = 0;
var _JSONP_RC = '';

function jsonp_handler(data, key){
	if(_JSONP_KV[key]){
		_JSONP_KV[key].func(data);
        document.body.removeChild(_JSONP_KV[key].node);
		delete _JSONP_KV[key];
	}
}


var _N_HANDLERS = {

};

/*
 * AJAX调用
 * N(method)
 * N(method, args)
 * N(method, callback_on_ok)
 * N(method, args, callback_on_ok)
 * N(method, callback_on_ok, callback_on_error)
 * N(method, args, callback_on_ok, callback_on_error)
 */
define(function(){
	function N(method, arg1, arg2, arg3){
		var arg, func_ok, func_er;
		var scriptNode, jsonpKey;
		var t1, t2, t3;
		var method_raw;
		t1 = typeof arg1;
		t2 = typeof arg2;
		t3 = typeof arg3;
		if(t1 == 'function'){
			func_ok = arg1;
			if(t2 == 'function'){
				func_er = arg2;
			}
		}else if(t2 == 'function'){
			func_ok = arg2
			if(t1 == 'object'){
				arg = arg1;
			}
			if(t3 == 'function'){
				func_er = arg3;
			}
		}else if(t3 == 'function'){
			func_er = arg3;
			if(t1 == 'object'){
				arg = arg1;
			}
		}else{
			if(t1 == 'object'){
				arg = arg1;
			}
		}
				
		arg = arg || {};
		
		func_ok = func_ok || function(){};
		func_er = func_er || function(){};
		
		jsonpKey = 'N_' + (_JSONP_CX ++);
		
		scriptNode = document.createElement('script');
		scriptNode.type = 'text/javascript';
		
		_JSONP_KV[jsonpKey] = { node : scriptNode, func : function(data){
//			try{
				method_raw = data.method.split('.');
				
				if(data.code > 0){
					t3 = 0;
					t2 = _N_HANDLERS;
					while(t3 < method_raw.length){
						if(t2[method_raw[t3]]){
							t2 = t2[method_raw[t3]];
							if(t2.ok){
								t2.ok(data);
								break;
							}
							t3 ++;
						}else{
							break;
						}
					}
					func_ok(data);
				}else{
					t3 = 0;
					t2 = _N_HANDLERS;
					while(t3 < method_raw.length){
						if(t2[method_raw[t3]]){
							t2 = t2[method_raw[t3]];
							if(t2.er){
								t2.er(data);
								break;
							}
							t3 ++;
						}else{
							break;
						}
					}
					func_er(data);
				}
//			}catch(e){
//				console.log([e, data]);
//			}
		}};
		t2 = _JSONP_RC + '?m=' + method + '&jsonp_handle=jsonp_handler&jsonp_key=' + jsonpKey;
		for(t1 in arg){
			t2 += '&' + t1 + '=' + encodeURIComponent(arg[t1]);
		}
		scriptNode.src = t2;
		document.body.appendChild(scriptNode);
	}
    N.listen = function(methodClass, listener){
        _N_HANDLERS[methodClass] = listener;
    }
    N.setURL = function(url){
        _JSONP_RC = url;
    }
	return N;
});